package cn.nexd.utils.framework.error;

import java.io.File;
import java.io.IOException;

import cn.nexd.utils.framework.tools.DateUtil;
import cn.nexd.utils.framework.tools.FileUtil;
import cn.nexd.utils.framework.tools.SDCardUtil;

/**
 * Nexd Crash and Exception Catch Class
 * <p/>
 * Signal Instance Class
 * <p/>
 * Created by wangxu on 16/8/9.
 */

public class NexdCrashException {

    private static String EXPORT_PATH = SDCardUtil.getSDCardPath();

    private static NexdCrashException nexdCrashException;

    /**
     * 获取单例对象
     *
     * @return
     */
    public static NexdCrashException getInstance() {
        if (nexdCrashException == null) {
            nexdCrashException = new NexdCrashException();
        }
        return nexdCrashException;
    }

    private NexdCrashException() {
    }

    private String getExportFilePath() {
        return EXPORT_PATH + "/nexd/error/" + DateUtil.getDate() + File.separator + DateUtil.getDate(DateUtil.DateStyle.YYYYMMDDhhmmss) + ".error";
    }


    /**
     * 设置全局异常捕获
     */
    public void setCaughtException() {
        Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());
    }


    private final class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            reportException(ex);
        }
    }


    /**
     * 导出异常信息到指定文件
     *
     * @param throwable exception
     */
    public void reportException(Throwable throwable) {
        if (throwable != null) {
            try {
                StackTraceElement[] stackTrace = throwable.getStackTrace();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("\n");
                stringBuilder.append(throwable.getMessage());

                for (StackTraceElement stackTraceElement : stackTrace) {
                    String className = stackTraceElement.getClassName();
                    String fileName = stackTraceElement.getFileName();
                    int lineNumber = stackTraceElement.getLineNumber();
                    String methodName = stackTraceElement.getMethodName();
                    stringBuilder.append("\n")
                            .append(fileName)
                            .append(" ")
                            .append(className)
                            .append(" ")
                            .append(lineNumber)
                            .append(" ")
                            .append(methodName);
                }
                stringBuilder.append("\n");
                FileUtil.writeFile(getExportFilePath(), stringBuilder.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
